package com.sanjiahantang.youjiarole.module.me.address.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.CheckBox;

import com.sanjiahantang.plugin.pickerview.OptionsPickerView;
import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseBean;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.city.models.ICityModel;
import com.sanjiahantang.youjiarole.module.city.models.impl.CityModel;
import com.sanjiahantang.youjiarole.module.common.models.IUserModel;
import com.sanjiahantang.youjiarole.module.common.models.impl.UserModel;
import com.sanjiahantang.youjiarole.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiarole.module.me.address.beans.AddressBean;
import com.sanjiahantang.youjiarole.module.me.address.beans.AddressDetailBean;
import com.sanjiahantang.youjiarole.module.me.address.views.AddressView;
import com.sanjiahantang.youjiarole.module.me.address.views.impl.AddressActivity;
import com.sanjiahantang.youjiarole.utils.SPUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zy on 2017/9/22.
 */
public class AddressPresenter extends BaseMvpPresenter<AddressView> {

    private QuickAdapter<AddressBean.Data> quickAdapter;
    private IUserModel userModel;
    private ICityModel cityModel;
    private AddressView.OnDetailLoadListener onDetailLoadListener;
    private OptionsPickerView pvOptionsDialog;

    private ArrayList<String> listProvince;
    private ArrayList<ArrayList<String>> listCity;
    private ArrayList<ArrayList<ArrayList<String>>> listArea;

    public AddressPresenter(){
        userModel = new UserModel();
        cityModel = new CityModel();
    }

    public void onPostResume(Context context) {
        onPostResume(context,null);
    }
    public void onPostResume(Context context, final BaseView.OnLoadListener listener) {
        mView.showProgress();
        Map<String, String> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE,"").toString());
        userModel.getAddressList(context,params,new CallBack<AddressBean>(){

            @Override
            public void onSuccess(AddressBean response, Context context, Object tag) {
                mView.hideProgress();
                if(response != null && response.getCode() == RESPONSE_CODE_SUC){
                    quickAdapter.clear();
                    if (listener != null){
                        listener.onLoad(response.getData().size());
                    }
                    if(response.getData().size()>0){
                        quickAdapter.addAll(response.getData());
                    }else
                        Utils.showToast(context,response.getMessage());
                }else if (response.getCode() == RESPONSE_CODE_SUC){
                    LoginActivity.logout(context);
                    Utils.showToast(context,response.getMessage());
                }
            }

            @Override
            public void onFailure(String message) {
                mView.hideProgress();
            }
        });
    }

    public void initAdapter(Context context, AddressView.OnLoadListener onLoadListener) {
        if(quickAdapter == null){
            quickAdapter = new QuickAdapter<AddressBean.Data>(context, R.layout.item_address) {
                @Override
                protected void convert(final BaseAdapterHelper helper, final AddressBean.Data item) {
                    helper.setText(R.id.txtName,item.getCustomerName());
                    helper.setText(R.id.txtPhone, item.getCellPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
                    helper.setText(R.id.txtAddress, item.getFullAddress());
                    //删除
                    helper.setOnClickListener(R.id.txtDelete, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Utils.showDialog((Activity) context, "提示", "确定要删除地址吗？", "", "", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Utils.dismissDialog();
                                    switch (view.getId()) {
                                        case R.id.txtDialogCancel:
                                            break;
                                        case R.id.txtDialogSure:
                                            loadDelete(context, item.getUcaId());

                                            break;
                                    }
                                }
                            });
                        }
                    });
                    //编辑
                    helper.setOnClickListener(R.id.txtEdit, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent itEdit = new Intent(context,AddressActivity.class);
                            itEdit.putExtra("address",item.getUcaId());
                            context.startActivity(itEdit);
                        }
                    });
                    //设置默认地址
                    helper.setOnClickListener(R.id.defaultAddress, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CheckBox checkBox = helper.getView(R.id.checkBox);
                            if (!checkBox.isChecked()){
                                editDefault(context, item.getUcaId(), 1);
                            }
                        }
                    });


                    boolean check = false;
                    if(item.getIsDefault() == 1)
                        check = true;
                    helper.setChecked(R.id.checkBox,check);
                }
            };
        }
        onLoadListener.initList(quickAdapter);
    }

    private void editDefault(Context context, int ucaId,int isDefault) {
        mView.showProgress();
        Map<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(AddressView.KEY_ID,String.valueOf(ucaId));
        params.put(KEY_PHONE,SPUtils.get(context,SPConfig.PHONE,"").toString());


        params.put(AddressView.KEY_PHONE,"");
        params.put(AddressView.KEY_NAME,"");
        params.put(AddressView.KEY_ADDRESS,"");
        params.put(AddressView.KEY_FULL_ADDRESS,"");
        params.put(AddressView.KEY_IS_DEFAULT,String.valueOf(isDefault));
        userModel.editDefaultAddress(context,params,new EditDefaultCallBack());
    }

    private void loadDelete(Context context, int id) {
        mView.showProgress();
        Map<String, String> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(AddressView.KEY_ID,String.valueOf(id));
        userModel.deleteAddress(context,params,new DeleteAddressCallBack());
    }

    public void addNewAddress(Context context,int type) {
        ((Activity) context).startActivityForResult(new Intent(context,AddressActivity.class).putExtra(KEY_TYPE,type),0xaa);
    }

    public void loadAddress(Context context, String id, AddressView.OnDetailLoadListener onDetailLoadListener) {
        this.onDetailLoadListener = onDetailLoadListener;
        Map<String,String> params = new HashMap<>();
        params.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        params.put(AddressView.KEY_ID,id);
        userModel.loadAddressDetail(context,params,new LoadAddressDetailCallBack());
    }

    /**
     *
     * @param context
     * @param customerName
     * @param fullAddress
     * @param cellPhone
     * @param id
     *
     * token
    query	string
    ucaId
    地址Id
    query	long
    phone
    客户账号
    query	string
    cellPhone
    手机号
    query	string
    customerName
    收货人姓名
    query	string
    address
    所在地
    query	string
    fullAddress
    详细地址
    query	string
    isDefault
     */
    public void saveAddress(Context context, String customerName, String fullAddress, String cellPhone, String address, String id,int isDefault) {

        Map<String,Object> params = new HashMap<>();
        params.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        params.put(AddressView.KEY_ID,id);
        params.put(KEY_PHONE,SPUtils.get(context,SPConfig.PHONE,"").toString());
        params.put(AddressView.KEY_PHONE,cellPhone);
        params.put(AddressView.KEY_NAME,customerName);
        params.put(AddressView.KEY_ADDRESS,address);
        params.put(AddressView.KEY_FULL_ADDRESS,fullAddress);
        params.put(AddressView.KEY_IS_DEFAULT,String.valueOf(isDefault));
        userModel.saveAddress(context,params,new SaveAddressCallBack());
    }

    public void loadPersonCityList(Context context, BaseView.OnLoadListener listener) {
        cityModel.getAllArea(context, listener);
    }

    public boolean onBackPressed() {
        if (pvOptionsDialog != null && pvOptionsDialog.isShowing()){
            pvOptionsDialog.dismiss();
            return true;
        }
        return false;
    }



    private class DeleteAddressCallBack implements CallBack<BaseBean>{

        @Override
        public void onSuccess(BaseBean response, Context context, Object tag) {
            mView.hideProgress();
            if(response.getCode() == RESPONSE_CODE_SUC)
                onPostResume(context);
            else if(response.getCode() == RESPONSE_CODE_SUC){
                goPageSimply(context,LoginActivity.class);
            }
            Utils.showToast(context,response.getMessage());
        }

        @Override
        public void onFailure(String message) {
            mView.hideProgress();
        }
    }

    private class EditDefaultCallBack implements CallBack<BaseBean>{

        @Override
        public void onSuccess(BaseBean response, Context context, Object tag) {
            mView.hideProgress();
            if(response.getCode() == RESPONSE_CODE_SUC)
                onPostResume(context);
            else if(response.getCode() == RESPONSE_CODE_SUC){
                LoginActivity.logout(context);
            }
            Utils.showToast(context,response.getMessage());
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }
   //保存收货地址
    private class SaveAddressCallBack implements CallBack<BaseBean>{

        @Override
        public void onSuccess(BaseBean response, Context context, Object tag) {
            hideProgress();
            if(response.getCode() == RESPONSE_CODE_SUC){
                ((Activity)context).setResult(Activity.RESULT_OK);
                ((Activity)context).finish();
                Utils.showToast(context,response.getMessage());
            }else if(response.getCode() == RESPONSE_CODE_SUC){
                LoginActivity.logout(context);
            }
            Utils.showToast(context,response.getMessage());
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }
    private class LoadAddressDetailCallBack implements CallBack<AddressDetailBean>{

        @Override
        public void onSuccess(AddressDetailBean response, Context context, Object tag) {
            hideProgress();
            onDetailLoadListener.loadData(response);
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }

    private void hideProgress() {
        if (mView != null) mView.hideProgress();
    }
}
